package com.ttpai.boot.lbs.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ttpai.boot.lbs.constant.BaiduLbsConst;
import com.ttpai.boot.lbs.model.RoutePlanReportVO;
import com.ttpai.boot.lbs.util.JsoupUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * Created by kail on 2017/2/26.
 */
@Service
public class BaiduLbsService {

    private static final Logger logger = LoggerFactory.getLogger(BaiduLbsService.class);

    private static final String AK = "ZGRIsTdTkiH3W5qZtvZIikgEuRCiyKky";

    private static final String[] TYPE = {"driving", "riding", "walking"};

    @Autowired
    private BaiduLbsConst baiduLbsConst;

    @Autowired
    private RoutePlanReportService routePlanReportService;

    /**
     * 根据城市和地址获取经纬度
     */
    public String fetchLngLat(String city, String address) {
        String url = "http://api.map.baidu.com/geocoder/v2/?callback=renderOption&output=xml&city=%s&address=%s&ak=" + baiduLbsConst.WEBAPI_AK;
        String realUrl = String.format(url, city, address.replaceAll("[\\(\\)（）]", ""));
        String bodyStr = JsoupUtil.get(realUrl);
        Document document = Jsoup.parse(bodyStr);
        String lat = document.select("lat").text();
        String lng = document.select("lng").text();
        lat = StringUtils.hasText(lat) ? lat : "0";
        lng = StringUtils.hasText(lng) ? lng : "0";
        return lng + "," + lat;
    }


    /**
     * 抓取某一天数据的经纬度信息
     */
    public void fetchLngLat(Date date) throws IOException {
        List<RoutePlanReportVO> reportVOS = routePlanReportService.selectRoutePlanReportByDate(date);

        for (RoutePlanReportVO report : reportVOS) {
            String[] lnglat = fetchLngLat(report.getBranchCityName(), report.getBranchAreaName() + " " + report.getAddress()).split(",");
            RoutePlanReportVO update = new RoutePlanReportVO();
            update.setId(report.getId());
            update.setLng(Double.valueOf(lnglat[0]));
            update.setLat(Double.valueOf(lnglat[1]));
            routePlanReportService.updateRoutePlanReportNotNull(update);

        }
    }

    /**
     * 驾车 http://api.map.baidu.com/routematrix/v2/driving?output=json&origins=40.45,116.34|40.54,116.35&destinations=40.34,116.45|40.35,116.46&ak=您的ak
     * 骑行 http://api.map.baidu.com/routematrix/v2/riding?output=json&origins=40.45,116.34|40.54,116.35&destinations=40.34,116.45|40.35,116.46&ak=您的ak
     * 步行 http://api.map.baidu.com/routematrix/v2/walking?output=json&origins=40.45,116.34|40.54,116.35&destinations=40.34,116.45|40.35,116.46&ak=您的ak
     */


    private static final String API_FORMAT = "http://api.map.baidu.com/routematrix/v2/%s?output=json&origins=%s&destinations=%s&ak=" + AK;


    public static String driving(String origins, String destinations) throws IOException {
        String url = String.format(API_FORMAT, TYPE[0], origins, destinations);
        return JsoupUtil.get(url);
    }

    public static String riding(String origins, String destinations) throws IOException {
        String url = String.format(API_FORMAT, TYPE[1], origins, destinations);
        return JsoupUtil.get(url);
    }

    public static String walking(String origins, String destinations) throws IOException {
        String url = String.format(API_FORMAT, TYPE[2], origins, destinations);
        return JsoupUtil.get(url);
    }


    /**
     * http://lbsyun.baidu.com/index.php?title=webapi/direction-api-v2
     * <p>
     * 金运路到丰庄 http://api.map.baidu.com/direction/v2/transit?origin=31.248395,121.362263&destination=31.247346,121.326116&ak=ZGRIsTdTkiH3W5qZtvZIikgEuRCiyKky&tactics_incity=5
     * 武宁路到七宝 http://api.map.baidu.com/direction/v2/transit?origin=31.16131,121.356011&destination=31.24026,121.436751&ak=ZGRIsTdTkiH3W5qZtvZIikgEuRCiyKky&tactics_incity=5
     * <p>
     * 31.16131,121.356011
     * 31.24026,121.436751
     */
    public String directionV2(double aLat, double aLng, double dlat, double dLng) {
        return directionV2(aLat, aLng, dlat, dLng, null);
    }

    /**
     * @param tacticsIncity 市内公交换乘策略 可选，0 推荐(默认)；1 少换乘；2 少步行；3 不坐地铁；4 时间短；5 地铁优先
     */
    public String directionV2(double aLat, double aLng, double dlat, double dLng, Integer tacticsIncity) {
        tacticsIncity = null == tacticsIncity ? 0 : tacticsIncity;

        String url = String.format("http://api.map.baidu.com/direction/v2/transit?origin=%s,%s&destination=%s,%s&tactics_incity=%s&ak=%s",
                aLat, aLng, dlat, dLng, tacticsIncity, AK);

        System.out.println(url);

        return JsoupUtil.getBodyText(url);
    }


    /**
     * 每公里用时5分钟左右
     */
    public static void main(String[] args) throws IOException {

        // {"status":0,"result":[{"distance":{"text":"7.7公里","value":7698},"duration":{"text":"13分钟","value":751}},{"distance":{"text":"15公里","value":14956},"duration":{"text":"27分钟","value":1635}}],"message":"成功"}
//        System.out.println(driving("31.240008,121.437236", "31.255901,121.369699|31.162281,121.347473"));//  智慧广场 -> 丰庄茶城|七宝 13分钟|27分钟
        // {"status":0,"result":[{"distance":{"text":"7.4公里","value":7423},"duration":{"text":"37分钟","value":2220}},{"distance":{"text":"14.6公里","value":14643},"duration":{"text":"1.2小时","value":4368}}],"message":"成功"}
//        System.out.println(riding("31.240008,121.437236", "31.255901,121.369699|31.162281,121.347473"));//  智慧广场 -> 丰庄茶城|七宝 37分钟|1.2小时
        // {"status":0,"result":[{"distance":{"text":"7.4公里","value":7370},"duration":{"text":"2小时","value":7363}},{"distance":{"text":"14.4公里","value":14419},"duration":{"text":"4小时","value":14401}}],"message":"成功"}
//        System.out.println(walking("31.240008,121.437236", "31.255901,121.369699|31.162281,121.347473"));//  智慧广场 -> 丰庄茶城|七宝 2小时|4小时

        BaiduLbsService baiduLbsService = new BaiduLbsService();
        String json = baiduLbsService.directionV2(31.16131, 121.35601, 31.24026, 121.436751, 5);

        JSONObject jsonObject = JSON.parseObject(json);
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray routes = result.getJSONArray("routes");
        JSONObject route = routes.getJSONObject(0);
        System.out.println(route.getInteger("duration"));

    }
}
